# coding=utf-8
import paramiko,time,base64

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())#做验证签名用
# 格式化成2016-03-20 11:45:39形式
sj = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
host = '127.0.0.1'
port = 22
name = 'root'
passwd = '1234567'

def Ssh(host,port,name,passwd,cmd):
	try:
		ssh.connect(host, port, username=name, password=passwd)  # ,pkey=key
		stdin,stdout,stderr = ssh.exec_command(cmd)
		print stdout.read()
		#print stderr.read()
		ssh.close()
	except Exception,e:
		print e

cmd = '7za a -t7z -r /root/web.7z /www/web/blog/*' #打包网站
sql = 'mysqldump -uroot -p123123 blog >/root/blog.sql' #备份数据库
Ssh(host,port,name,passwd,cmd)
print 'webbak successful'
Ssh(host,port,name,passwd,sql)
print 'mysqlbak successful'
time.sleep(3)
def Scp(host,port,name,passwd):
	try:
		# 建立一个加密的管道
		scp = paramiko.Transport((host, port))
		# 建立连接
		scp.connect(username=name, password=passwd)
		# 建立一个sftp客户端对象，通过ssh transport操作远程文件
		sftp = paramiko.SFTPClient.from_transport(scp)
		# Copy a remote file (remotepath) from the SFTP server to the local host
		sftp.get('/root/web.7z', '%s.7z' % (str(sj)))# 下载文件以及下载保存文件名
		sftp.get('/root/blog.sql', '%s.sql' % (str(sj)))  # 下载文件以及下载保存文件名
		print 'donw success!!!'
		scp.close()
		Ssh(host, port, name, passwd, 'rm -rf /root/web.7z|rm -rf /root/blog.sql')# 删除备份文件
		print 'del success!!!'
		#Ssh(host, port, name, passwd, 'rm -rf /root/blog.sql')  # 删除备份文件

	except Exception,e:
		print e
Scp(host,port,name,passwd)